import React, { useState, useEffect, useRef } from 'react';
import {
  Card,
  Row,
  Col,
  Progress,
  Statistic,
  Alert,
  Table,
  Tag,
  Divider,
  Switch,
  Button,
  Space,
  notification,
  Descriptions,
  Spin,
} from 'antd';
import {
  ReloadOutlined,
  PlayCircleOutlined,
  PauseCircleOutlined,
  WarningOutlined,
  CheckCircleOutlined,
  CloseCircleOutlined,
  InfoCircleOutlined,
} from '@ant-design/icons';
import ReactECharts from 'echarts-for-react';
import { monitorApi } from '@/services/api';
import io, { Socket } from 'socket.io-client';
import dayjs from 'dayjs';

interface SystemMetrics {
  cpu: number;
  memory: number;
  disk: number;
  network: {
    in: number;
    out: number;
  };
  timestamp: number;
  processes: {
    total: number;
    running: number;
  };
  uptime: number;
  loadAverage: number[];
}

interface SystemAlert {
  type: 'info' | 'warning' | 'error';
  title: string;
  message: string;
  timestamp: number;
}

const SystemMonitor: React.FC = () => {
  const [realTimeEnabled, setRealTimeEnabled] = useState(true);
  const [currentMetrics, setCurrentMetrics] = useState<SystemMetrics | null>(null);
  const [metricsHistory, setMetricsHistory] = useState<SystemMetrics[]>([]);
  const [systemInfo, setSystemInfo] = useState<any>(null);
  const [appMetrics, setAppMetrics] = useState<any>(null);
  const [healthCheck, setHealthCheck] = useState<any>(null);
  const [logAnalysis, setLogAnalysis] = useState<any>(null);
  const [alerts, setAlerts] = useState<SystemAlert[]>([]);
  const [loading, setLoading] = useState(true);
  
  const socketRef = useRef<Socket | null>(null);

  // 获取初始数据
  const refreshMetrics = async () => {
    try {
      const response = await monitorApi.getSystemMetrics();
      setCurrentMetrics(response.data);
    } catch (error) {
      console.error('Failed to fetch system metrics:', error);
    }
  };

  const refreshHistory = async () => {
    try {
      const response = await monitorApi.getMetricsHistory('1h');
      setMetricsHistory(response.data);
    } catch (error) {
      console.error('Failed to fetch metrics history:', error);
    }
  };

  // WebSocket 连接和实时数据
  useEffect(() => {
    if (realTimeEnabled) {
      connectWebSocket();
    } else {
      disconnectWebSocket();
    }

    return () => {
      disconnectWebSocket();
    };
  }, [realTimeEnabled]);

  const connectWebSocket = () => {
    const token = localStorage.getItem('token');
    if (!token) return;

    socketRef.current = io('http://localhost:3001/monitor', {
      auth: {
        token: `Bearer ${token}`,
      },
    });

    const socket = socketRef.current;

    socket.on('connect', () => {
      console.log('WebSocket connected');
      socket.emit('subscribe-metrics');
    });

    socket.on('initial-data', (data) => {
      setCurrentMetrics(data.systemMetrics);
      setSystemInfo(data.systemInfo);
      setAppMetrics(data.appMetrics);
      setHealthCheck(data.healthCheck);
      setLoading(false);
    });

    socket.on('real-time-metrics', (data) => {
      setCurrentMetrics(data.systemMetrics);
      setAppMetrics(data.appMetrics);
      setHealthCheck(data.healthCheck);
      setLogAnalysis(data.logAnalysis);
      
      // 更新历史数据
      setMetricsHistory(prev => {
        const newHistory = [...prev, data.systemMetrics];
        return newHistory.slice(-50); // 保留最近50个数据点
      });
    });

    socket.on('system-alerts', (newAlerts: SystemAlert[]) => {
      setAlerts(prev => [...newAlerts, ...prev].slice(0, 10)); // 保留最近10个告警
      
      // 显示通知
      newAlerts.forEach(alert => {
        notification[alert.type]({
          message: alert.title,
          description: alert.message,
          duration: alert.type === 'error' ? 0 : 4.5,
        });
      });
    });

    socket.on('error', (error) => {
      console.error('WebSocket error:', error);
      notification.error({
        message: '连接错误',
        description: error.message,
      });
    });

    socket.on('disconnect', () => {
      console.log('WebSocket disconnected');
    });
  };

  const disconnectWebSocket = () => {
    if (socketRef.current) {
      socketRef.current.disconnect();
      socketRef.current = null;
    }
  };

  const handleRefresh = () => {
    if (!realTimeEnabled) {
      refreshMetrics();
      refreshHistory();
    }
  };

  useEffect(() => {
    if (!realTimeEnabled) {
      refreshMetrics();
      refreshHistory();
    }
  }, []);

  const getStatusColor = (value: number, thresholds = { warning: 70, danger: 85 }) => {
    if (value >= thresholds.danger) return '#ff4d4f';
    if (value >= thresholds.warning) return '#faad14';
    return '#52c41a';
  };

  const getHealthStatusIcon = (status: string) => {
    switch (status) {
      case 'healthy':
        return <CheckCircleOutlined style={{ color: '#52c41a' }} />;
      case 'unhealthy':
        return <CloseCircleOutlined style={{ color: '#ff4d4f' }} />;
      default:
        return <InfoCircleOutlined style={{ color: '#1890ff' }} />;
    }
  };

  // CPU 使用率趋势图
  const getCpuTrendOption = () => ({
    title: {
      text: 'CPU 使用率趋势',
      left: 'center',
      textStyle: { fontSize: 14 },
    },
    grid: { top: 40, right: 20, bottom: 40, left: 50 },
    xAxis: {
      type: 'category',
      data: metricsHistory.map(m => dayjs(m.timestamp).format('HH:mm:ss')),
      axisLabel: { fontSize: 10 },
    },
    yAxis: {
      type: 'value',
      min: 0,
      max: 100,
      axisLabel: {
        formatter: '{value}%',
        fontSize: 10,
      },
    },
    series: [{
      data: metricsHistory.map(m => m.cpu),
      type: 'line',
      smooth: true,
      lineStyle: { color: '#1890ff' },
      areaStyle: { opacity: 0.3 },
    }],
    tooltip: {
      trigger: 'axis',
      formatter: (params: any) => {
        const data = params[0];
        return `${data.name}<br/>CPU: ${data.value}%`;
      },
    },
  });

  // 内存使用率趋势图
  const getMemoryTrendOption = () => ({
    title: {
      text: '内存使用率趋势',
      left: 'center',
      textStyle: { fontSize: 14 },
    },
    grid: { top: 40, right: 20, bottom: 40, left: 50 },
    xAxis: {
      type: 'category',
      data: metricsHistory.map(m => dayjs(m.timestamp).format('HH:mm:ss')),
      axisLabel: { fontSize: 10 },
    },
    yAxis: {
      type: 'value',
      min: 0,
      max: 100,
      axisLabel: {
        formatter: '{value}%',
        fontSize: 10,
      },
    },
    series: [{
      data: metricsHistory.map(m => m.memory),
      type: 'line',
      smooth: true,
      lineStyle: { color: '#52c41a' },
      areaStyle: { opacity: 0.3 },
    }],
    tooltip: {
      trigger: 'axis',
      formatter: (params: any) => {
        const data = params[0];
        return `${data.name}<br/>内存: ${data.value}%`;
      },
    },
  });

  // 网络流量图
  const getNetworkTrendOption = () => ({
    title: {
      text: '网络流量趋势',
      left: 'center',
      textStyle: { fontSize: 14 },
    },
    grid: { top: 40, right: 20, bottom: 40, left: 50 },
    legend: { top: 25, itemWidth: 10, itemHeight: 10, textStyle: { fontSize: 10 } },
    xAxis: {
      type: 'category',
      data: metricsHistory.map(m => dayjs(m.timestamp).format('HH:mm:ss')),
      axisLabel: { fontSize: 10 },
    },
    yAxis: {
      type: 'value',
      axisLabel: {
        formatter: '{value}KB/s',
        fontSize: 10,
      },
    },
    series: [
      {
        name: '入流量',
        data: metricsHistory.map(m => m.network?.in || 0),
        type: 'line',
        smooth: true,
        lineStyle: { color: '#1890ff' },
      },
      {
        name: '出流量',
        data: metricsHistory.map(m => m.network?.out || 0),
        type: 'line',
        smooth: true,
        lineStyle: { color: '#f5222d' },
      },
    ],
    tooltip: {
      trigger: 'axis',
    },
  });

  const alertColumns = [
    {
      title: '时间',
      dataIndex: 'timestamp',
      key: 'timestamp',
      width: 120,
      render: (timestamp: number) => dayjs(timestamp).format('HH:mm:ss'),
    },
    {
      title: '类型',
      dataIndex: 'type',
      key: 'type',
      width: 80,
      render: (type: string) => {
        const colorMap = { info: 'blue', warning: 'orange', error: 'red' };
        return <Tag color={colorMap[type as keyof typeof colorMap]}>{type.toUpperCase()}</Tag>;
      },
    },
    {
      title: '标题',
      dataIndex: 'title',
      key: 'title',
      width: 150,
    },
    {
      title: '消息',
      dataIndex: 'message',
      key: 'message',
      ellipsis: true,
    },
  ];

  if (loading) {
    return (
      <div style={{ padding: '24px', textAlign: 'center' }}>
        <Spin size="large" />
        <div style={{ marginTop: '16px' }}>正在加载系统监控数据...</div>
      </div>
    );
  }

  return (
    <div style={{ padding: '24px' }}>
      {/* 控制面板 */}
      <Card style={{ marginBottom: '24px' }}>
        <Row align="middle" justify="space-between">
          <Col>
            <Space>
              <span>实时监控：</span>
              <Switch
                checked={realTimeEnabled}
                onChange={setRealTimeEnabled}
                checkedChildren={<PlayCircleOutlined />}
                unCheckedChildren={<PauseCircleOutlined />}
              />
              <Divider type="vertical" />
              <Button
                icon={<ReloadOutlined />}
                onClick={handleRefresh}
                disabled={realTimeEnabled}
              >
                刷新
              </Button>
            </Space>
          </Col>
          <Col>
            <Space>
              {healthCheck && (
                <Space>
                  {getHealthStatusIcon(healthCheck.status)}
                  <span>系统状态：{healthCheck.status === 'healthy' ? '正常' : '异常'}</span>
                </Space>
              )}
            </Space>
          </Col>
        </Row>
      </Card>

      {/* 系统告警 */}
      {alerts.length > 0 && (
        <Alert
          message="系统告警"
          description={
            <div style={{ maxHeight: '100px', overflowY: 'auto' }}>
              {alerts.slice(0, 3).map((alert, index) => (
                <div key={index} style={{ marginBottom: '4px' }}>
                  <Tag color={alert.type === 'error' ? 'red' : alert.type === 'warning' ? 'orange' : 'blue'}>
                    {alert.type.toUpperCase()}
                  </Tag>
                  {alert.title}: {alert.message}
                </div>
              ))}
            </div>
          }
          type="warning"
          icon={<WarningOutlined />}
          showIcon
          closable
          style={{ marginBottom: '24px' }}
          onClose={() => setAlerts([])}
        />
      )}

      {/* 系统指标卡片 */}
      <Row gutter={[16, 16]} style={{ marginBottom: '24px' }}>
        <Col xs={24} sm={12} md={6}>
          <Card>
            <Statistic
              title="CPU 使用率"
              value={currentMetrics?.cpu || 0}
              precision={1}
              suffix="%"
              valueStyle={{ color: getStatusColor(currentMetrics?.cpu || 0) }}
            />
            <Progress
              percent={currentMetrics?.cpu || 0}
              strokeColor={getStatusColor(currentMetrics?.cpu || 0)}
              size="small"
              showInfo={false}
            />
          </Card>
        </Col>
        <Col xs={24} sm={12} md={6}>
          <Card>
            <Statistic
              title="内存使用率"
              value={currentMetrics?.memory || 0}
              precision={1}
              suffix="%"
              valueStyle={{ color: getStatusColor(currentMetrics?.memory || 0) }}
            />
            <Progress
              percent={currentMetrics?.memory || 0}
              strokeColor={getStatusColor(currentMetrics?.memory || 0)}
              size="small"
              showInfo={false}
            />
          </Card>
        </Col>
        <Col xs={24} sm={12} md={6}>
          <Card>
            <Statistic
              title="磁盘使用率"
              value={currentMetrics?.disk || 0}
              precision={1}
              suffix="%"
              valueStyle={{ color: getStatusColor(currentMetrics?.disk || 0, { warning: 80, danger: 90 }) }}
            />
            <Progress
              percent={currentMetrics?.disk || 0}
              strokeColor={getStatusColor(currentMetrics?.disk || 0, { warning: 80, danger: 90 })}
              size="small"
              showInfo={false}
            />
          </Card>
        </Col>
        <Col xs={24} sm={12} md={6}>
          <Card>
            <Statistic
              title="系统负载"
              value={currentMetrics?.loadAverage?.[0] || 0}
              precision={2}
              valueStyle={{ color: '#1890ff' }}
            />
            <div style={{ fontSize: '12px', color: '#666', marginTop: '8px' }}>
              1min: {currentMetrics?.loadAverage?.[0]?.toFixed(2)} |
              5min: {currentMetrics?.loadAverage?.[1]?.toFixed(2)} |
              15min: {currentMetrics?.loadAverage?.[2]?.toFixed(2)}
            </div>
          </Card>
        </Col>
      </Row>

      {/* 趋势图表 */}
      <Row gutter={[16, 16]} style={{ marginBottom: '24px' }}>
        <Col xs={24} lg={8}>
          <Card style={{ height: '300px' }}>
            <ReactECharts option={getCpuTrendOption()} style={{ height: '250px' }} />
          </Card>
        </Col>
        <Col xs={24} lg={8}>
          <Card style={{ height: '300px' }}>
            <ReactECharts option={getMemoryTrendOption()} style={{ height: '250px' }} />
          </Card>
        </Col>
        <Col xs={24} lg={8}>
          <Card style={{ height: '300px' }}>
            <ReactECharts option={getNetworkTrendOption()} style={{ height: '250px' }} />
          </Card>
        </Col>
      </Row>

      {/* 详细信息 */}
      <Row gutter={[16, 16]}>
        <Col xs={24} lg={12}>
          <Card title="系统信息">
            {systemInfo && (
              <Descriptions column={1} size="small">
                <Descriptions.Item label="操作系统">{systemInfo.platform}</Descriptions.Item>
                <Descriptions.Item label="架构">{systemInfo.arch}</Descriptions.Item>
                <Descriptions.Item label="版本">{systemInfo.release}</Descriptions.Item>
                <Descriptions.Item label="主机名">{systemInfo.hostname}</Descriptions.Item>
                <Descriptions.Item label="CPU 核心数">{systemInfo.cpus}</Descriptions.Item>
                <Descriptions.Item label="总内存">{systemInfo.totalMemory} GB</Descriptions.Item>
                <Descriptions.Item label="Node.js 版本">{systemInfo.nodeVersion}</Descriptions.Item>
                <Descriptions.Item label="运行时间">{Math.floor(systemInfo.uptime / 3600)} 小时</Descriptions.Item>
              </Descriptions>
            )}
          </Card>
        </Col>
        <Col xs={24} lg={12}>
          <Card title="系统告警历史">
            <Table
              columns={alertColumns}
              dataSource={alerts}
              pagination={false}
              size="small"
              scroll={{ y: 200 }}
              rowKey={(record, index) => index}
            />
          </Card>
        </Col>
      </Row>

      {/* 应用程序指标 */}
      {appMetrics && (
        <Card title="应用程序指标" style={{ marginTop: '16px' }}>
          <Row gutter={16}>
            <Col span={6}>
              <Statistic title="进程 ID" value={appMetrics.pid} />
            </Col>
            <Col span={6}>
              <Statistic 
                title="运行时间" 
                value={Math.floor(appMetrics.uptime / 3600)} 
                suffix="小时"
              />
            </Col>
            <Col span={6}>
              <Statistic 
                title="堆内存使用" 
                value={appMetrics.memoryUsage?.heapUsed} 
                suffix="MB"
              />
            </Col>
            <Col span={6}>
              <Statistic 
                title="堆内存总量" 
                value={appMetrics.memoryUsage?.heapTotal} 
                suffix="MB"
              />
            </Col>
          </Row>
        </Card>
      )}
    </div>
  );
};

export default SystemMonitor;